package com.videoadmin.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.videoadmin.factory.DAOFactory;
import com.videoadmin.pojo.User;
import com.videoadmin.utils.Md5;

public class AdminLoginServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public AdminLoginServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String truePath = "/jsp/main.jsp"; // 验证正确路径
		String errorPath = "/admin_login.jsp";
		String adminname = request.getParameter("adminname");
		String password = request.getParameter("password");
		List<String> info = new ArrayList<String>();
		boolean flag = false;
		if (adminname == null || "".equals(adminname)) {
			info.add("用户名不能为空！");
		}
		if (password == null || "".equals(password)) {
			info.add("密码不能为空！");
		}
		if (info.size() == 0) {
			User user = new User();
			user.setUser_Name(adminname);
			user.setUser_Password(Md5.getMd5String(password));
			try {
				if (DAOFactory.getIUserDAOInstance().testUser(user)) {
					// 设置session属性
					request.getSession().setAttribute("username", adminname);
					flag = true;
				} else {
					info.add("用户名或密码错误！");
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		request.setAttribute("err", info);
		request.getRequestDispatcher(flag ? truePath : errorPath).forward(
				request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
